package com.xhsj.user.pms.patent.service;

import com.google.common.collect.Lists;
import com.xhsj.user.config.UploadPathConfig;
import com.xhsj.user.generalprocess.entity.TbPamGeneralProcessHiTask;
import com.xhsj.user.generalprocess.entity.TbPamGeneralProcessTask;
import com.xhsj.user.generalprocess.mapper.TbPamGeneralProcessHiTaskMapper;
import com.xhsj.user.generalprocess.mapper.TbPamGeneralProcessTaskMapper;
import com.xhsj.user.generalprocess.service.TbPamGeneralProcessTaskService;
import com.xhsj.user.generalprocess.vo.GeneralAuditHistoryVo;
import com.xhsj.user.generalprocess.vo.GeneralAuditVo;
import com.xhsj.user.generalprocess.vo.GeneralRunTaskVo;
import com.xhsj.user.hr.system.mapper.TbGlobalUserMapper;
import com.xhsj.user.pms.overseas.dto.GmMonitorListAduitDto;
import com.xhsj.user.pms.overseas.dto.MonitorListDto;
import com.xhsj.user.pms.overseas.dto.PatentListByCountryNameDto;
import com.xhsj.user.pms.overseas.entity.TbPamOverseasPrompt;
import com.xhsj.user.pms.overseas.query.ApplyNumAndPublicNumQuery;
import com.xhsj.user.pms.overseas.query.CaseTreeListQuery;
import com.xhsj.user.pms.overseas.service.TbPamOverseasPromptService;
import com.xhsj.user.pms.overseas.service.TbPamOverseasRegionalDetailsService;
import com.xhsj.user.pms.patent.domain.PatentFile;
import com.xhsj.user.pms.patent.domain.TbPamOverseasApply;
import com.xhsj.user.pms.patent.domain.TbPamOverseasApplyCountry;
import com.xhsj.user.pms.patent.dto.FindRunTaskDto;
import com.xhsj.user.pms.patent.mapper.*;
import com.xhsj.user.pms.patent.domain.TbPamOverseasApplyFile;
import com.xhsj.user.pms.patent.domain.*;
import com.xhsj.user.hr.base.BaseService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.xhsj.user.pms.patent.query.OverseasApplyAuditTransferOutListQuery;
import com.xhsj.user.pms.patent.query.PatentListByCountryNameQuery;
import com.xhsj.user.pms.patent.vo.*;
import com.xhsj.user.properties.RoleKeyNameProperites;
import com.xhsj.user.sms.transfer.mapper.TbTaskTransferMapper;
import com.xhsj.user.utils.IdGen;
import com.xhsj.user.utils.StringUtils;
import com.xhsj.user.utils.UserUtils;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.BeanUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.*;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import java.io.Serializable;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import lombok.extern.slf4j.Slf4j;

/**
 * <p>
 * 专利模块海外申请表 服务实现类
 * </p>
 *
 * @author suxiaolin
 * @since Jan 25, 2021 10:54:00 AM
 */
@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
//@CacheConfig(cacheNames = "TbPamOverseasApply")
public class TbPamOverseasApplyService extends BaseService<TbPamOverseasApplyMapper, TbPamOverseasApply> {
    @Autowired
    private TbPamOverseasApplyMapper dao;

    @Autowired
    private TbPamGeneralProcessTaskService tbPamGeneralProcessTaskService;

    @Autowired
    private RoleKeyNameProperites roleKeyNameProperites;

    @Autowired
    private TbGlobalUserMapper userMapper;

    @Autowired
    private TbPamOverseasApplyFileMapper tbPamOverseasApplyFileMapper;

    @Autowired
    private PatentFileMapper patentFileMapper;

    @Autowired
    private TbTaskTransferMapper tbTaskTransferMapper;

    @Autowired
    private UploadPathConfig uploadPath;

    @Autowired
    private DisclosureMapper disclosureMapper;

    @Autowired
    private DisclosureInventorMapper disclosureInventorMapper;

    @Autowired
    private TbPamOverseasApplyCountryMapper tbPamOverseasApplyCountryMapper;

    @Autowired
    private TbPamGeneralProcessTaskMapper tbPamGeneralProcessTaskMapper;

    @Autowired
    private TbPamGeneralProcessHiTaskMapper tbPamGeneralProcessHiTaskMapper;

    @Autowired
    private TbPamOverseasRegionalDetailsService tbPamOverseasRegionalDetailsService;

    @Autowired
    private PatentApplyProjectMapper patentApplyProjectMapper;

    /**
     * 保存
     *
     * @author suxiaolin
     * @date Jan 25, 2021 10:54:00 AM
     */
    @Autowired
    private TbPamOverseasPromptService tbPamOverseasPromptService;

    @Autowired
    private TbPamInventorProposalIprMapper tbPamInventorProposalIprMapper;

    /**
     * 保存
     *
     * @author suxiaolin
     * @date Jan 25, 2021 10:54:00 AM
     */
    @Override
    //@CacheEvict(cacheNames="TbPamOverseasApply", allEntries=true)
    public boolean save(TbPamOverseasApply entity) {
        return super.save(entity);
    }

    /**
     * 通过id获取数据
     *
     * @author suxiaolin
     * @date Jan 25, 2021 10:54:00 AM
     */
    @Override
    //@Cacheable(key = "#id",sync = true)
    public TbPamOverseasApply getById(Serializable id) {
        return super.getById(id);
    }

    /**
     * 通过id删除数据
     *
     * @author suxiaolin
     * @date Jan 25, 2021 10:54:00 AM
     */
    @Override
    //@CacheEvict(cacheNames="TbPamOverseasApply", allEntries=true)
    public boolean removeById(Serializable id) {
        return super.removeById(id);
    }

    /**
     * 批量删除数据
     *
     * @author suxiaolin
     * @date Jan 25, 2021 10:54:00 AM
     */
    //@CacheEvict(cacheNames="SysDict", allEntries=true)
    @Override
    public boolean removeByIds(Collection<? extends Serializable> idList) {
        return super.removeByIds(idList);
    }

    /**
     * 分页查询数据
     *
     * @author suxiaolin
     * @date Jan 25, 2021 10:54:00 AM
     */
    //@Cacheable(key = "#data",sync = true)
    public IPage<TbPamOverseasApply> selectPage(Map<String, Object> data) {
        int currentPage = 1;
        if (!Objects.isNull(data.get("page"))) {
            currentPage = (Integer) data.get("page");
        }
        int pageSize = 20;
        if (!Objects.isNull(data.get("size"))) {
            pageSize = (Integer) data.get("size");
        }

        TbPamOverseasApply entity = JSON.parseObject(JSON.toJSONString(data), TbPamOverseasApply.class);
        Page<TbPamOverseasApply> page = new Page(currentPage, pageSize);
        QueryWrapper<TbPamOverseasApply> wrapper = new QueryWrapper(entity);
        return super.selectPage(page, wrapper);
    }

    /**
     * 查询所有数据
     *
     * @author suxiaolin
     * @date Jan 25, 2021 10:54:00 AM
     */
    @Override
    //@Cacheable(value = "TbPamOverseasApply",sync = true)
    public List<TbPamOverseasApply> selectAll() {
        return super.selectAll();
    }


    /**
     * 流程启动
     *
     * @author 苏小林
     * @date 2021/1/25 11:12
     * @param: data
     */
    public void startProcess(TbPamOverseasApply data) throws Exception {

        this.saveData(data);


        String ledSeniorProcessEngineer = roleKeyNameProperites.getLedSeniorProcessEngineer();
        Long roleId = userMapper.getRoleIdByRoleKeyName(ledSeniorProcessEngineer);
        if (roleId == null) {
            throw new Exception("LED高级工艺工程师角色不存在,请先完善角色。");
        }
        List<Long> userIdByRoleName = userMapper.getUserIdByRoleName(ledSeniorProcessEngineer);
        if (userIdByRoleName == null || userIdByRoleName.size() == 0)
            throw new Exception("角色-LED高级工艺工程师下无在职用户存在");

        GeneralAuditVo generalAuditVo = new GeneralAuditVo();
        generalAuditVo.setDataId(data.getId());
        generalAuditVo.setRoleIds(Arrays.asList(roleId));
        generalAuditVo.setOpinionText(data.getOpinionText());
        this.fillParams(generalAuditVo);

        tbPamGeneralProcessTaskService.startProcess(generalAuditVo, generalCallableVo -> {
            data.setNodeId(generalCallableVo.getNodeId());
            data.setNodeName(generalCallableVo.getNodeName());
            data.setProcessTaskId(generalCallableVo.getProcessTaskId());

            // 修改相关信息
            dao.updateById(data);
        });


    }

    public void saveData(TbPamOverseasApply data) throws Exception {
        super.save(data);
        tbPamOverseasApplyFileMapper.deleteByApplyId(data.getId());

        List<TbPamOverseasApplyFile> applyFileList = data.getApplyFileList();
        if (applyFileList != null && applyFileList.size() > 0) {
            for (TbPamOverseasApplyFile tbPamOverseasApplyFile : applyFileList) {

                tbPamOverseasApplyFile.setCreateDate(tbPamOverseasApplyFile.getCreateDate() == null ? new Date() : tbPamOverseasApplyFile.getCreateDate());
                tbPamOverseasApplyFile.setUpdateDate(tbPamOverseasApplyFile.getUpdateDate() == null ? new Date() : tbPamOverseasApplyFile.getUpdateDate());
                tbPamOverseasApplyFile.setCreateBy(tbPamOverseasApplyFile.getCreateBy() == null ? UserUtils.getLoginAppUser().getUserId() : tbPamOverseasApplyFile.getCreateBy());
                tbPamOverseasApplyFile.setUpdateBy(tbPamOverseasApplyFile.getUpdateBy() == null ? UserUtils.getLoginAppUser().getUserId() : tbPamOverseasApplyFile.getUpdateBy());
//                if (StringUtils.isBlank(tbPamOverseasApplyFile.getCreateBy())) {
//                    tbPamOverseasApplyFile.setCreateBy(UserUtils.getLoginAppUser().getUserId());
//                    tbPamOverseasApplyFile.setUpdateBy(UserUtils.getLoginAppUser().getUserId());
//                    tbPamOverseasApplyFile.setCreateDate(new Date());
//                    tbPamOverseasApplyFile.setUpdateDate(new Date());
//                }

                tbPamOverseasApplyFile.setOverseasApplyId(data.getId());
                int insert = tbPamOverseasApplyFileMapper.insert(tbPamOverseasApplyFile);
                if (insert == 0) {
                    throw new Exception("保存文件出错");
                }
            }

        }
    }

    /**
     * 填充参数
     *
     * @author 苏小林
     * @date 2021/1/22 17:48
     * @param: generalAuditVo
     */
    private void fillParams(GeneralAuditVo generalAuditVo) {
        generalAuditVo.setProcessType("foreign_apply");
        generalAuditVo.setNodeTableName("tb_pam_general_node");
        generalAuditVo.setTaskTableName("tb_pam_general_process_task");
        generalAuditVo.setHiTaskTableName("tb_pam_general_process_hi_task");
        generalAuditVo.setOpinionFileTableName("tb_pam_general_opinion_file");

    }

    /**
     * 查询正在执行中任务
     *
     * @author 苏小林
     * @date 2021/1/25 15:01
     */
    public IPage<FindRunTaskVo> findRunTask(FindRunTaskDto baseParam) throws Exception {

        // 查询正在执行中任务
        GeneralAuditVo generalAuditVo = new GeneralAuditVo();
        generalAuditVo.setUserIds(Arrays.asList(UserUtils.getLoginAppUser().getUserId()));
        if (generalAuditVo.getUserIds().size() == 0) {
            throw new Exception("当前登录用户异常");
        }
        List<Long> roleIds = userMapper.getRoleIdsByUserId(UserUtils.getLoginAppUser().getUserId());
        generalAuditVo.setRoleIds(roleIds);
        this.fillParams(generalAuditVo);
//        IPage<GeneralRunTaskVo> iPage = tbPamGeneralProcessTaskService.findRunTask(generalAuditVo);
//        List<GeneralRunTaskVo> runTask = iPage.getRecords();
        Page<FindRunTaskVo> page = new Page<>(baseParam.getPage(), baseParam.getSize());
        IPage<FindRunTaskVo> list = dao.findRunTask(page, generalAuditVo, baseParam);
//
//        if (runTask != null && runTask.size() > 0) {
//            List<Long> dataIds = runTask.stream().map(generalHiTaskVo -> generalHiTaskVo.getDataId()).collect(Collectors.toList());
//            List<FindRunTaskVo> list = dao.findRunTaskByDataIds(dataIds,baseParam);
//            for (FindRunTaskVo findRunTaskVo : list) {
//                for (GeneralRunTaskVo generalRunTaskVo : runTask) {
//                    if (findRunTaskVo.getDataId().equals(generalRunTaskVo.getDataId())) {
//                        // 填充数据
//                        findRunTaskVo.setProcessTaskId(generalRunTaskVo.getProcessTaskId());
//
//                        break;
//                    }
//                }
//            }
//            IPage<FindRunTaskVo> resultPage = new Page<>();
//            resultPage.setRecords(list);
//            resultPage.setPages(iPage.getPages());
//            resultPage.setTotal(iPage.getTotal());
//
//            return resultPage;
//        }

//        IPage<FindRunTaskVo> resultPage = new Page<>();
        return list;

    }

    /**
     * 查询历史任务
     *
     * @author 苏小林
     * @date 2021/1/25 15:02
     */
    public IPage<FindHiTaskVo> findHiTask(FindRunTaskDto baseParam) throws Exception {
        // 查询历史任务列表
        GeneralAuditVo generalAuditVo = new GeneralAuditVo();
//        generalAuditVo.setPage(baseParam.getPage());
//        generalAuditVo.setSize(baseParam.getSize());
        generalAuditVo.setUserIds(Arrays.asList(UserUtils.getLoginAppUser().getUserId()));
        this.fillParams(generalAuditVo);
        Page<FindRunTaskVo> page = new Page<>(baseParam.getPage(), baseParam.getSize());
        IPage<FindHiTaskVo> list = dao.findHiTaskList(page, generalAuditVo, baseParam);

//        IPage<GeneralHiTaskVo> iPage = tbPamGeneralProcessTaskService.findHiTask(generalAuditVo);
//        List<GeneralHiTaskVo> hiTask = iPage.getRecords();

//        if (hiTask != null && hiTask.size() > 0) {
//            List<Long> dataIds = hiTask.stream().map(generalHiTaskVo -> generalHiTaskVo.getDataId()).collect(Collectors.toList());
//            List<FindHiTaskVo> list = dao.findHiTaskByDataIds(dataIds,baseParam);
//            for (FindHiTaskVo findHiTaskVo : list) {
//                for (GeneralHiTaskVo generalHiTaskVo : hiTask) {
//                    if (findHiTaskVo.getDataId().equals(generalHiTaskVo.getDataId())) {
//                        findHiTaskVo.setExamineStatus(generalHiTaskVo.getExamineStatus());
//                        findHiTaskVo.setUpdateName(generalHiTaskVo.getUpdateName());
//                        break;
//                    }
//                }
//            }
//            IPage<FindHiTaskVo> resultPage = new Page<>();
//            resultPage.setRecords(list);
//            resultPage.setPages(iPage.getPages());
//            resultPage.setTotal(iPage.getTotal());
//            return resultPage;
//        }

//        IPage<FindHiTaskVo> resultPage = new Page<>();
        return list;
    }

    /**
     * 通过dataId查询数据
     *
     * @author 苏小林
     * @date 2021/1/27 14:16
     * @param: dataId
     * @return: com.xhsj.user.pms.patent.domain.TbPamOverseasApply
     */
    public TbPamOverseasApply getByDataId(Long dataId) {

        TbPamOverseasApply tbPamOverseasApply = dao.getByDataId(dataId);
        if (tbPamOverseasApply != null) {
            QueryWrapper<TbPamOverseasApplyFile> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("overseas_apply_id", tbPamOverseasApply.getId());
            queryWrapper.orderByDesc("create_date");
            List<TbPamOverseasApplyFile> tbPamOverseasApplyFiles = tbPamOverseasApplyFileMapper.selectList(queryWrapper);
            tbPamOverseasApply.setApplyFileList(tbPamOverseasApplyFiles);
        }

        return tbPamOverseasApply;

    }

    /**
     * 处理流程节点2-流程专员编写案例
     *
     * @author 苏小林
     * @date 2021/1/27 15:58
     * @param: entity
     */
    public TbPamOverseasApply handleProcessNode_2(OverseasApplyAuditVo entity) throws Exception {

        // 组装审核数据
        GeneralAuditVo generalAuditVo = this.jointParams(entity);

        Integer status = entity.getStatus();
        if (status == 0) { // 通过
            Long ipr = entity.getIpr();
            if (ipr == null) {
                throw new Exception("ipr为空"+entity.getName());
            }
            generalAuditVo.setUserIds(Arrays.asList(entity.getIpr()));
        }
        TbPamOverseasApply tbPamOverseasApply = new TbPamOverseasApply();
        BeanUtils.copyProperties(entity, tbPamOverseasApply);

//            int i = 1/0;
        // 处理流程
        tbPamGeneralProcessTaskService.handleProcess(generalAuditVo, generalCallableVo -> {
            tbPamOverseasApply.setNodeId(generalCallableVo.getNodeId());
            tbPamOverseasApply.setNodeName(generalCallableVo.getNodeName());
            tbPamOverseasApply.setProcessTaskId(generalCallableVo.getProcessTaskId());
        });


        // 保存海外申请数据
        this.saveData(tbPamOverseasApply);
        return tbPamOverseasApply;
    }

    /**
     * 处理流程节点3-IPR编写完整申请文件
     *
     * @author 苏小林
     * @date 2021/1/27 16:54
     * @param: entity
     */
    public TbPamOverseasApply handleProcessNode_3(OverseasApplyAuditVo entity) throws Exception {

        GeneralAuditVo generalAuditVo = this.jointParams(entity);

        Integer status = entity.getStatus();
        String roleName = null;
        if (status == 0) { // 通过
            roleName = roleKeyNameProperites.getZszl1();
            Long roleId = userMapper.getRoleIdByRoleKeyName(roleName);
            if (roleId == null) {
                throw new Exception("资深专利工程师角色不存在,请先完善角色。");
            }
            generalAuditVo.setRoleIds(Arrays.asList(roleId));
        } else if (status == 1) { // 退回-流程专员审核
            roleName = roleKeyNameProperites.getAssistantName();
            Long roleId = userMapper.getRoleIdByRoleKeyName(roleName);
            if (roleId == null) {
                throw new Exception("没有可用的流程专员角色");
            }
            generalAuditVo.setRoleIds(Arrays.asList(roleId));
        }
        List<Long> userIdByRoleName = userMapper.getUserIdByRoleName(roleName);
        if (userIdByRoleName == null || userIdByRoleName.size() == 0)
            throw new Exception("下一节点角色下无在职用户存在");

        TbPamOverseasApply tbPamOverseasApply = new TbPamOverseasApply();
        BeanUtils.copyProperties(entity, tbPamOverseasApply);

        // 处理流程
        tbPamGeneralProcessTaskService.handleProcess(generalAuditVo, generalCallableVo -> {
            tbPamOverseasApply.setNodeId(generalCallableVo.getNodeId());
            tbPamOverseasApply.setNodeName(generalCallableVo.getNodeName());
            tbPamOverseasApply.setProcessTaskId(generalCallableVo.getProcessTaskId());
        });


        // 保存海外申请数据
        this.saveData(tbPamOverseasApply);
        return tbPamOverseasApply;
    }

    /**
     * 处理流程节点4和节点5-主管审核和总经理审核
     *
     * @author 苏小林
     * @date 2021/1/27 15:43
     * @return: com.xhsj.user.utils.Message
     */
    public TbPamOverseasApply handleProcessNode_4_5(OverseasApplyAuditVo entity) throws Exception {
        GeneralAuditVo generalAuditVo = this.jointParams(entity);

        TbPamOverseasApply tbPamOverseasApply = new TbPamOverseasApply();
        BeanUtils.copyProperties(entity, tbPamOverseasApply);

        Integer status = entity.getStatus();
        String roleName = null;
        switch (status) {
            // 0通过   2闭案
            case 0:
            case 2:
                Long nodeId = entity.getNodeId();
                if (nodeId == 4 && status == 0) { // 主管审核
                    roleName = roleKeyNameProperites.getGeneralManager();
                    Long roleId = userMapper.getRoleIdByRoleKeyName(roleName);
                    if (roleId == null) {
                        throw new Exception("没有可用的总经理角色");
                    }
                    generalAuditVo.setRoleIds(Arrays.asList(roleId));
                } else if (nodeId == 5) { // 总经理审核
                    roleName = roleKeyNameProperites.getAssistantName();
                    Long roleId = userMapper.getRoleIdByRoleKeyName(roleName);
                    if (roleId == null) {
                        throw new Exception("没有可用的流程专员角色");
                    }
                    generalAuditVo.setRoleIds(Arrays.asList(roleId));
                }
                if (status == 0) {
                    List<Long> userIdByRoleName = userMapper.getUserIdByRoleName(roleName);
                    if (userIdByRoleName == null || userIdByRoleName.size() == 0)
                        throw new Exception("下一节点角色下无在职用户存在");
                }

                break;
            // 退回
            case 1:
                Long ipr = entity.getIpr();
                if (ipr == null) {
                    throw new Exception("IPR为空");
                }
                generalAuditVo.setUserIds(Arrays.asList(ipr));
                break;
        }

        // 处理流程
        tbPamGeneralProcessTaskService.handleProcess(generalAuditVo, generalCallableVo -> {
            tbPamOverseasApply.setNodeId(generalCallableVo.getNodeId());
            tbPamOverseasApply.setNodeName(generalCallableVo.getNodeName());
            tbPamOverseasApply.setProcessTaskId(generalCallableVo.getProcessTaskId());
        });
        // 保存海外申请数据
        this.saveData(tbPamOverseasApply);
        return tbPamOverseasApply;
    }


    /**
     * 处理流程节点6-处理委托提交
     *
     * @author 苏小林
     * @date 2021/1/27 17:54
     * @param: entity
     */
    public void handleProcessNode_6(OverseasApplyAuditVo entity) throws Exception {
        GeneralAuditVo generalAuditVo = this.jointParams(entity);

        Integer status = entity.getStatus();
        if (status == 0) { // 通过
            generalAuditVo.setUserIds(Arrays.asList(UserUtils.getLoginAppUser().getUserId()));
        }
        TbPamOverseasApply tbPamOverseasApply = new TbPamOverseasApply();
        BeanUtils.copyProperties(entity, tbPamOverseasApply);

        // 处理流程
        tbPamGeneralProcessTaskService.handleProcess(generalAuditVo, generalCallableVo -> {
            tbPamOverseasApply.setNodeId(generalCallableVo.getNodeId());
            tbPamOverseasApply.setNodeName(generalCallableVo.getNodeName());
        });

        // 保存海外申请数据
        this.saveData(tbPamOverseasApply);

    }

    /**
     * 处理流程节点7-处理授权通过
     *
     * @author 苏小林
     * @date 2021/1/29 14:31
     * @param: entity
     */
    public void handleProcessNode_7(OverseasApplyAuditVo entity) throws Exception {
        GeneralAuditVo generalAuditVo = this.jointParams(entity);

        TbPamOverseasApply tbPamOverseasApply = new TbPamOverseasApply();
        BeanUtils.copyProperties(entity, tbPamOverseasApply);

        // 处理流程
        tbPamGeneralProcessTaskService.handleProcess(generalAuditVo, generalCallableVo -> {
            tbPamOverseasApply.setNodeId(generalCallableVo.getNodeId());
            tbPamOverseasApply.setNodeName(generalCallableVo.getNodeName());
        });
        // 保存海外申请数据
        this.saveData(tbPamOverseasApply);
    }

    private GeneralAuditVo jointParams(OverseasApplyAuditVo entity) {
        // 组装审核数据
        GeneralAuditVo generalAuditVo = new GeneralAuditVo();
        generalAuditVo.setNodeId(entity.getNodeId());
        generalAuditVo.setDataId(entity.getId());
        generalAuditVo.setProcessTaskId(entity.getProcessTaskId());
        generalAuditVo.setStatus(entity.getStatus());
        generalAuditVo.setOpinionText(entity.getOpinionText());
        generalAuditVo.setOpinionFiles(entity.getOpinionFiles());
        this.fillParams(generalAuditVo);
        return generalAuditVo;
    }


    /**
     * 查询审核历史
     *
     * @author 苏小林
     * @date 2021/1/29 10:26
     * @param: dataId
     * @param: page
     * @param: size
     * @return: com.baomidou.mybatisplus.core.metadata.IPage<com.xhsj.user.generalprocess.vo.GeneralAuditHistoryVo>
     */
    public IPage<GeneralAuditHistoryVo> getAuditHistory(Long dataId, int page, int size) throws Exception {
        GeneralAuditVo generalAuditVo = new GeneralAuditVo();
        generalAuditVo.setPage(page);
        generalAuditVo.setSize(size);
        generalAuditVo.setDataId(dataId);
        this.fillParams(generalAuditVo);
        IPage<GeneralAuditHistoryVo> iPage = tbPamGeneralProcessTaskService.findAuditHistory(generalAuditVo);
        return iPage;
    }


    /**
     * @Description:国内案件提醒ipr流程专员审批
     * @Param:com.xhsj.user.pms.overseas.dto.GmMonitorListAduitDto
     * @Author: liuqinghua
     * @Date: 2021/1/26
     */
    public TbPamOverseasApply gmMonitorListAduit(GmMonitorListAduitDto param) throws Exception {
        // ipr流程专员审核通过-专利助理
        String disclosureId = param.getDisclosureId();
        TbPamOverseasApply apply = new TbPamOverseasApply();
        if (param.getStatus() == 0) {
            // 获取国内 1国内申请文件
            this.getDomesticApplyFile(disclosureId, apply.getApplyFileList());
            BeanUtils.copyProperties(param, apply);
            Date priorityDate = apply.getPriorityDate();
            if (priorityDate != null) {
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(priorityDate);
                calendar.add(Calendar.MONTH, param.getTerm());
                apply.setPriorityApplyExpiration(calendar.getTime());

                //            判断
                Calendar calendar1 = Calendar.getInstance();
                calendar1.setTime(priorityDate);
                calendar1.add(Calendar.MONTH, 30);
                apply.setPctApplyExpiration(calendar1.getTime());
            }

            apply.setName(param.getDisclosureName());
            // pct届满日  优先权日+是30个月 默认计算加上

            // 获取申请号和公开号和专利表id
            ApplyNumAndPublicNumQuery applyNumAndPublicNum = dao.getApplyNumAndPublicNum(param.getNum());
            if (applyNumAndPublicNum != null) {
                String applicationNum = applyNumAndPublicNum.getApplicationNum() == null ? "" : applyNumAndPublicNum.getApplicationNum();
                apply.setDomesticTreeValue(applicationNum);
                apply.setPatentId(applyNumAndPublicNum.getPatentId());
            }
            this.startProcess(apply);
        }
        // 保存专利海外申请国家
        this.saveCountry(param.getCountryNames(), apply.getId());
        // 保存专利模块国内案件提示信息
        TbPamOverseasPrompt tbPamOverseasPrompt = new TbPamOverseasPrompt();
        tbPamOverseasPrompt.setDisclosureId(disclosureId);
        tbPamOverseasPrompt.setRegionalDetailsId(param.getRegionalDetailsId());
        if (!tbPamOverseasPromptService.save(tbPamOverseasPrompt)) {
            throw new Exception("保存专利模块国内案件提示信息异常");
        }
        return apply;
    }

    // 获取国内 1国内申请文件
    public void getDomesticApplyFile(String disclosureId, List<TbPamOverseasApplyFile> tbPamOverseasApplyFileList) {
        List<PatentFile> applyFileList = patentFileMapper.getFileListByDiscId(disclosureId, 5);
        for (PatentFile file : applyFileList) {
            TbPamOverseasApplyFile tbPamOverseasApplyFile = new TbPamOverseasApplyFile();
            BeanUtils.copyProperties(file, tbPamOverseasApplyFile);
            tbPamOverseasApplyFile.setFileType(1);
            tbPamOverseasApplyFile.setFileUrl(file.getUrl());
            tbPamOverseasApplyFile.setCreateName(file.getOwnerUserFullName());
            tbPamOverseasApplyFile.setCreateBy(Long.valueOf(file.getOwnerAs()));
            tbPamOverseasApplyFile.setUpdateBy(Long.valueOf(file.getOwnerAs()));
            tbPamOverseasApplyFile.setUpdateDate(file.getUploadTime());
            tbPamOverseasApplyFile.setCreateDate(file.getUploadTime());
            tbPamOverseasApplyFileList.add(tbPamOverseasApplyFile);
        }
        ;
    }

    // 案件树
    public Set<CaseTreeListQuery> caseTreeList(String searchName) {
        List<CaseTreeListQuery> caseTreeListQueries = dao.caseTreeList(searchName);
        Set<CaseTreeListQuery> caseTreeListQuerySet = new HashSet<>();
        Set<CaseTreeListQuery> caseOneTreeListQuerySet = new HashSet<>();
        // 顶级
        CaseTreeListQuery query = new CaseTreeListQuery();
        query.setLabel("案件树");
        query.setParentId("0");
        caseTreeListQuerySet.add(query);
        // 获取父级
        for (CaseTreeListQuery set : caseTreeListQuerySet) {
            for (CaseTreeListQuery caseTreeListQuery : caseTreeListQueries) {
                CaseTreeListQuery caseTree = new CaseTreeListQuery();
                caseTree.setId(caseTreeListQuery.getDisclosureId());
                String archivesNum = caseTreeListQuery.getArchivesNum() == null ? "" : caseTreeListQuery.getArchivesNum();
                String domesticTreeValue = caseTreeListQuery.getDomesticTreeValue() == null ? "" : caseTreeListQuery.getDomesticTreeValue();
                if (domesticTreeValue != "") {
                    domesticTreeValue = " " + domesticTreeValue;
                }
                caseTree.setLabel(archivesNum + domesticTreeValue);
                caseTree.setParentId("1");
                caseTree.setDisclosureId(caseTreeListQuery.getDisclosureId());
                caseOneTreeListQuerySet.add(caseTree);
                set.setChildren(caseOneTreeListQuerySet);
            }
        }
        // 为一级菜单设置子菜单，getChild是递归调用的
        for (CaseTreeListQuery set : caseTreeListQuerySet) {
            Set<CaseTreeListQuery> children = set.getChildren();
            for (CaseTreeListQuery menu : children) {
                menu.setChildren(getTwoChild(menu.getId(), caseTreeListQueries));
            }
        }
        return caseTreeListQuerySet;
    }

    /**
     * 递归查找二级菜单
     *
     * @param id       当前菜单id
     * @param rootMenu 要查找的列表
     * @return
     */
    private Set<CaseTreeListQuery> getTwoChild(String id, List<CaseTreeListQuery> rootMenu) {
        // 子菜单
        Set<CaseTreeListQuery> twoChildList = new HashSet<>();
        for (CaseTreeListQuery menu : rootMenu) {
            // 遍历所有节点，将父菜单id与传过来的id比较
            if (StringUtils.isNotBlank(menu.getDisclosureId())) {
                if (menu.getDisclosureId().equals(id)) {
                    CaseTreeListQuery twoMenu = new CaseTreeListQuery();
                    String overseasArchivesNum = menu.getOverseasArchivesNum() == null ? "" : menu.getOverseasArchivesNum();
                    String overseasApplyNum = menu.getOverseasApplyNum() == null ? "" : menu.getOverseasApplyNum();
                    String value = "";
                    if (overseasApplyNum != "") {
                        value = " " + overseasApplyNum;
                    }
                    twoMenu.setLabel(overseasArchivesNum + value);
                    twoMenu.setId(menu.getId());
                    twoMenu.setParentId(menu.getDisclosureId());
                    twoChildList.add(twoMenu);
                }
            }
        }
        // 把子菜单的子菜单再循环一遍
//          for (CaseTreeListQuery menu : twoChildList) {
//         // 递归
//          menu.setChildren(getChild(menu.getId(), rootMenu));
//          }

        // 递归退出条件
        if (twoChildList.size() == 0) {
            return null;
        }
        return twoChildList;
    }

    private Set<CaseTreeListQuery> getChild(String id, List<CaseTreeListQuery> rootMenu) {
        // 子菜单
        Set<CaseTreeListQuery> childList = new HashSet<>();
        for (CaseTreeListQuery menu : rootMenu) {
            // 遍历所有节点，将父菜单id与传过来的id比较
            if (StringUtils.isNotBlank(menu.getDisclosureId())) {
                if (menu.getDisclosureId().equals(id)) {
                    childList.add(menu);
                }
            }
        }
        // 把子菜单的子菜单再循环一遍
        for (CaseTreeListQuery menu : childList) {// 没有url子菜单还有子菜单
            // 递归
            menu.setChildren(getChild(menu.getId(), rootMenu));
        } // 递归退出条件
        if (childList.size() == 0) {
            return null;
        }
        return childList;
    }


    // 国内案件提醒总经理审批页面展示
    public Map<String, Object> gmMonitorListAduitPageView(String disclosureId) {
        // 获取国内案件基础信息
        Map<String, Object> map = disclosureMapper.getDisclosureDetailPlanToWrite(disclosureId);
        // 权重
        List<DisclosureInventor> inventorList = disclosureInventorMapper.getListByDisclosureId(disclosureId);
        map.put("inventorList", inventorList);
        // 获取对应的交底书ipr
        List<Long> adviceIpr = tbPamInventorProposalIprMapper.getAdviceIpr(disclosureId);
        // 获取国内 1国内申请文件
        List<PatentFile> patentFileListByDiscId = patentFileMapper.getFileListByDiscId(disclosureId, 5);
        Long ipr = null;
        if (adviceIpr.size() > 0) {
            ipr = adviceIpr.get(0);
        }
        map.put("adviceIprs", ipr);
        map.put("patentFileList", patentFileListByDiscId);
        return map;
    }

    @Transactional(rollbackFor = Exception.class)
    public void deleteOverseasApplyFile(Long id, String path) throws IOException {
        int i = tbPamOverseasApplyFileMapper.delById(id);
        if (i > 0) {
            this.deleteFile(path);
        }
    }

    public void deleteFile(String path) throws IOException {
        path = uploadPath.getPath() + "/" + path.substring(path.lastIndexOf("download/") + 9);
        Path filePath = Paths.get(path);
        File toFile = filePath.toFile();
        boolean exists = toFile.exists();
        if (exists) {
            Files.delete(filePath);
        }
    }


    public IPage<OverseasApplyListVo> findApplyList(Map<String, Object> data) {
        int currentPage = 1;
        if (!Objects.isNull(data.get("page"))) {
            currentPage = (Integer) data.get("page");
        }
        int pageSize = 20;
        if (!Objects.isNull(data.get("size"))) {
            pageSize = (Integer) data.get("size");
        }

        Page<TbPamOverseasApply> page = new Page(currentPage, pageSize);

        return dao.findApplyList(page,
                StringUtils.getLongValue(data, "regionalDetailsId"),
                StringUtils.getStringValue(data, "overseasOfficeNum"),
                StringUtils.getStringValue(data, "name"),
                StringUtils.getStringValue(data, "priorityNum"),
                StringUtils.getStringValue(data, "relatedNum"),
                StringUtils.getIntegerValue(data, "applyTypeId"),
                StringUtils.getStringValue(data, "countryName"),
                StringUtils.getIntegerValue(data, "curNodeId"),
                StringUtils.getStringValue(data, "archivesNum"),
                StringUtils.getStringValue(data, "overseasApplyNum")
        );

    }

    /**
     * 保存数据接口
     *
     * @author 苏小林
     * @date 2021/3/2 16:12
     * @param: entity
     */
    public void saveData(OverseasApplyAuditVo entity) throws Exception {

        TbPamOverseasApply tbPamOverseasApply = new TbPamOverseasApply();
        BeanUtils.copyProperties(entity, tbPamOverseasApply);
        // 保存海外申请数据
        this.saveData(tbPamOverseasApply);
    }

    /**
     * 处理流程10-技术负责人(LED高级工艺工程师)审核进入总经理确认
     *
     * @author 苏小林
     * @date 2021/3/9 16:48
     * @param: enterCountryVo
     */
    public TbPamOverseasApply handleProcessNode_10(EnterCountryVo entity) throws Exception {

        // 保存海外申请国家数据
        List<String> countryNames = entity.getCountryNames();
        if ((countryNames.isEmpty() || countryNames.size() == 0) && entity.getStatus() == 0) {
            throw new Exception("申请国家不能为空");
        }

        OverseasApplyAuditVo overseasApplyAuditVo = new OverseasApplyAuditVo();
        BeanUtils.copyProperties(entity, overseasApplyAuditVo);

        // 组装审核数据
        GeneralAuditVo generalAuditVo = this.jointParams(overseasApplyAuditVo);

        Integer status = entity.getStatus();
        if (status == 1) { // 驳回
            // 申请人id
            String fullNameByUserId = userMapper.getFullNameByUserId(String.valueOf(entity.getApplyUserId()));
            if (StringUtils.isBlank(fullNameByUserId))
                throw new Exception("申请人已离职，不能继续下一步");
            generalAuditVo.setUserIds(Arrays.asList(entity.getApplyUserId()));
        }
        if (status == 0) { // 通过
            String generalManager = roleKeyNameProperites.getGeneralManager();
            Long roleId = userMapper.getRoleIdByRoleKeyName(generalManager);
            if (roleId == null) {
                throw new Exception("没有可用的总经理角色");
            }
            List<Long> userIdByRoleName = userMapper.getUserIdByRoleName(generalManager);
            if (userIdByRoleName == null || userIdByRoleName.size() == 0)
                throw new Exception("角色-总经理下无在职用户存在");
            generalAuditVo.setRoleIds(Arrays.asList(roleId));
        }

        TbPamOverseasApply tbPamOverseasApply = new TbPamOverseasApply();
        BeanUtils.copyProperties(entity, tbPamOverseasApply);
//            int i = 1/0;
        // 处理流程
        generalAuditVo.setOpinionText(entity.getOpinionText());
        tbPamGeneralProcessTaskService.handleProcess(generalAuditVo, generalCallableVo -> {
            tbPamOverseasApply.setNodeId(generalCallableVo.getNodeId());
            tbPamOverseasApply.setNodeName(generalCallableVo.getNodeName());
            tbPamOverseasApply.setProcessTaskId(generalCallableVo.getProcessTaskId());
        });

        // 修改申请表节点相关信息
        this.updateById(tbPamOverseasApply);

        String collect = countryNames.stream().collect(Collectors.joining(","));
        // 删除对应的国家
        tbPamOverseasApplyCountryMapper.deleteByDataId(entity.getId());
        TbPamOverseasApplyCountry applyCountry = new TbPamOverseasApplyCountry();
        applyCountry.setDataId(entity.getId());
        applyCountry.setCountryName(collect);
        applyCountry.setCreateBy(UserUtils.getLoginAppUser().getUserId());
        applyCountry.setCreateDate(new Date());
        tbPamOverseasApplyCountryMapper.insert(applyCountry);
        return tbPamOverseasApply;
    }

    /**
     * 处理流程11-总经理审核进入国家
     *
     * @author 苏小林
     * @date 2021/3/9 17:29
     * @param: enterCountryVo
     */
    public TbPamOverseasApply handleProcessNode_11(EnterCountryVo entity) throws Exception {

        OverseasApplyAuditVo overseasApplyAuditVo = new OverseasApplyAuditVo();
        BeanUtils.copyProperties(entity, overseasApplyAuditVo);

        // 组装审核数据
        GeneralAuditVo generalAuditVo = this.jointParams(overseasApplyAuditVo);

        Integer status = entity.getStatus();
        if (status == 0) { // 通过 -流程专员审核
            String assistantName = roleKeyNameProperites.getAssistantName();
            Long roleId = userMapper.getRoleIdByRoleKeyName(assistantName);
            if (roleId == null) {
                throw new Exception("没有可用的流程专员角色");
            }
            List<Long> userIdByRoleName = userMapper.getUserIdByRoleName(assistantName);
            if (userIdByRoleName == null || userIdByRoleName.size() == 0)
                throw new Exception("角色-流程专员下无在职用户存在");

            generalAuditVo.setRoleIds(Arrays.asList(roleId));

            TbPamOverseasApply tbPamOverseasApply = new TbPamOverseasApply();
            BeanUtils.copyProperties(entity, tbPamOverseasApply);
            // 处理流程
            tbPamGeneralProcessTaskService.handleProcess(generalAuditVo, generalCallableVo -> {
                tbPamOverseasApply.setNodeId(generalCallableVo.getNodeId());
                tbPamOverseasApply.setNodeName(generalCallableVo.getNodeName());
                tbPamOverseasApply.setProcessTaskId(generalCallableVo.getProcessTaskId());
            });

            // 修改申请表节点相关信息
            this.updateById(tbPamOverseasApply);
            List<String> countryNames = entity.getCountryNames();


            if (!countryNames.isEmpty() && countryNames.size() == 1) {
                return tbPamOverseasApply;
            }

            // 查询海外申请数据
            TbPamOverseasApply byDataId = dao.getByDataId(entity.getId());

            // 查询海外申请文件
            QueryWrapper<TbPamOverseasApplyFile> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("overseas_apply_id", entity.getId());
            List<TbPamOverseasApplyFile> tbPamOverseasApplyFiles = tbPamOverseasApplyFileMapper.selectList(queryWrapper);

            // 查询当前数据正在执行中任务
            List<TbPamGeneralProcessTask> runTasks = tbPamGeneralProcessTaskMapper.findByDataIdAndType(entity.getId(), "foreign_apply");

            // 查询当前数据历史任务
            List<TbPamGeneralProcessHiTask> hiTasks = tbPamGeneralProcessHiTaskMapper.findHisTaskByDataIdAndType(entity.getId(), "foreign_apply");

            TbPamGeneralProcessTask processTask = runTasks.get(0);

            Iterator<TbPamGeneralProcessHiTask> iterator = hiTasks.iterator();
            while (iterator.hasNext()) {
                TbPamGeneralProcessHiTask next = iterator.next();
                if (processTask.getId().equals(next.getId())) {
                    iterator.remove();
                    break;
                }
            }
            // 删除数据
            tbPamOverseasApplyCountryMapper.deleteByDataId(entity.getId());

            // 保存和目前流程相关的一条数据
            TbPamOverseasApplyCountry applyCountry = new TbPamOverseasApplyCountry();
            applyCountry.setDataId(entity.getId());
            applyCountry.setCountryName(countryNames.get(0));
            applyCountry.setCreateBy(UserUtils.getLoginAppUser().getUserId());
            applyCountry.setCreateDate(new Date());
            tbPamOverseasApplyCountryMapper.insert(applyCountry);

            // 删除第一条数据
            countryNames.remove(0);

            for (String countryName : countryNames) {
                // 保存一条新的申请数据
                byDataId.setId(null);
                dao.insert(byDataId);

                // 保存海外申请国家数据
                TbPamOverseasApplyCountry applyCountry_1 = new TbPamOverseasApplyCountry();
                applyCountry_1.setDataId(byDataId.getId());
                applyCountry_1.setCountryName(countryName);
                applyCountry_1.setCreateBy(UserUtils.getLoginAppUser().getUserId());
                applyCountry_1.setCreateDate(new Date());
                tbPamOverseasApplyCountryMapper.insert(applyCountry_1);

                // 保存海外申请文件
                if (!tbPamOverseasApplyFiles.isEmpty()) {
                    for (TbPamOverseasApplyFile tbPamOverseasApplyFile : tbPamOverseasApplyFiles) {
                        tbPamOverseasApplyFile.setId(null);
                        tbPamOverseasApplyFile.setOverseasApplyId(byDataId.getId());
                        tbPamOverseasApplyFileMapper.insert(tbPamOverseasApplyFile);
                    }
                }


                if (runTasks != null) {
                    TbPamGeneralProcessTask processTask1 = runTasks.get(0);
                    processTask1.setDataId(byDataId.getId());
                    processTask1.setId(null);
                    this.saveRunAndHiTask(processTask1);
                }

                // 保存历史任务
                for (TbPamGeneralProcessHiTask hiTask : hiTasks) {
                    hiTask.setDataId(byDataId.getId());
                    hiTask.setId(IdGen.snowId());
                    tbPamGeneralProcessHiTaskMapper.saveHistory(hiTask, "tb_pam_general_process_hi_task");
                }
            }
            return  tbPamOverseasApply;
        } else if (status == 1) {

            String ledSeniorProcessEngineer = roleKeyNameProperites.getLedSeniorProcessEngineer();
            Long roleId = userMapper.getRoleIdByRoleKeyName(ledSeniorProcessEngineer);
            if (roleId == null) {
                throw new Exception("LED高级工艺工程师角色不存在,请先完善角色。");
            }
            List<Long> userIdByRoleName = userMapper.getUserIdByRoleName(ledSeniorProcessEngineer);
            if (userIdByRoleName == null || userIdByRoleName.size() == 0)
                throw new Exception("角色-LED高级工艺工程师下无在职用户存在");
            generalAuditVo.setRoleIds(Arrays.asList(roleId));
            // 处理流程
            tbPamGeneralProcessTaskService.handleProcess(generalAuditVo, generalCallableVo -> {
                TbPamOverseasApply tbPamOverseasApply2 = new TbPamOverseasApply();
                tbPamOverseasApply2.setId(entity.getId());
                tbPamOverseasApply2.setNodeId(generalCallableVo.getNodeId());
                tbPamOverseasApply2.setNodeName(generalCallableVo.getNodeName());
                dao.updateNodeIdAndNodeName(tbPamOverseasApply2);
            });

        }
        return null;
    }


    private void saveRunAndHiTask(TbPamGeneralProcessTask processTask1) {
        // 保存正在执行任务
        tbPamGeneralProcessTaskMapper.saveTask(processTask1, "tb_pam_general_process_task");

        // 保存历史任务
        TbPamGeneralProcessHiTask hiTask = new TbPamGeneralProcessHiTask();
        BeanUtils.copyProperties(processTask1, hiTask);
        hiTask.setExamineStatus(0);

        tbPamGeneralProcessHiTaskMapper.saveHistory(hiTask, "tb_pam_general_process_hi_task");

    }

    /***
     * 查询转出海外专利审核任务列表
     * @author 苏小林
     * @date 2021/6/22 13:26
     * @param: entity
     * @return: com.baomidou.mybatisplus.core.metadata.IPage<com.xhsj.user.pms.patent.vo.OverseasApplyAuditTransferOutListVo>
     */
    public IPage<OverseasApplyAuditTransferOutListVo> findOverseasApplyAuditTransferOutList(OverseasApplyAuditTransferOutListQuery entity) throws Exception {

        if (entity.getTaskType() == 0) { // 个人任务
            System.err.println(999);
            return this.findOverseasApplyPersonalTransferOutList(entity);

        }

        FindRunTaskDto findRunTaskDto = new FindRunTaskDto();
        findRunTaskDto.setPage(entity.getPageNum());
        findRunTaskDto.setSize(entity.getPageSize());
        IPage<FindRunTaskVo> iPage = this.findRunTask(findRunTaskDto);

        List<OverseasApplyAuditTransferOutListVo> resultList = Lists.newArrayList();
        for (FindRunTaskVo record : iPage.getRecords()) {
            OverseasApplyAuditTransferOutListVo overseasApplyAuditTransferOutListVo = new OverseasApplyAuditTransferOutListVo();
            BeanUtils.copyProperties(record, overseasApplyAuditTransferOutListVo);
            Map<String, String> maps = tbTaskTransferMapper.getUserIdByDataIdAndModelType(record.getProcessTaskId(), 3);
            if (maps != null) {

                List<Object> userLists = Lists.newArrayList();
                Object user_id = maps.get("user_id");
                Object department_id = maps.get("department_id");
                String id = maps.get("id");
                userLists.add(department_id);
                userLists.add(user_id);
                overseasApplyAuditTransferOutListVo.setUserList(userLists);
                overseasApplyAuditTransferOutListVo.setTransferId(id);

            }

            resultList.add(overseasApplyAuditTransferOutListVo);
        }

        IPage<OverseasApplyAuditTransferOutListVo> iPage_1 = new Page<>();
        iPage_1.setRecords(resultList);
        iPage_1.setTotal(iPage.getTotal());
        iPage_1.setPages(iPage.getPages());


        return iPage_1;

    }

    /**
     * 查询转出个人任务
     *
     * @author 苏小林
     * @date 2021/6/24 16:09
     * @param: entity
     * @return: com.baomidou.mybatisplus.core.metadata.IPage<com.xhsj.user.pms.patent.vo.OverseasApplyAuditTransferOutListVo>
     */
    private IPage<OverseasApplyAuditTransferOutListVo> findOverseasApplyPersonalTransferOutList(OverseasApplyAuditTransferOutListQuery entity) {

        Page<TbPamOverseasApply> page = new Page<>(entity.getPageNum(), entity.getPageSize());
        QueryWrapper<TbPamOverseasApply> wrapper = new QueryWrapper<>();
        wrapper.eq("create_by", UserUtils.getLoginAppUser().getUserId());
        IPage<TbPamOverseasApply> iPage = dao.selectPage(page, wrapper);
        if (iPage == null) {
            IPage<OverseasApplyAuditTransferOutListVo> iPage_1 = new Page<>();
            return iPage_1;
        }


        List<OverseasApplyAuditTransferOutListVo> resultList = Lists.newArrayList();
        for (TbPamOverseasApply record : iPage.getRecords()) {
            OverseasApplyAuditTransferOutListVo overseasApplyAuditTransferOutListVo = new OverseasApplyAuditTransferOutListVo();
            BeanUtils.copyProperties(record, overseasApplyAuditTransferOutListVo);

            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            overseasApplyAuditTransferOutListVo.setPriorityDate(simpleDateFormat.format(record.getPriorityDate()));
            overseasApplyAuditTransferOutListVo.setDataId(record.getId());
            overseasApplyAuditTransferOutListVo.setProcessTaskId(record.getId());

            Map<String, String> maps = tbTaskTransferMapper.getUserIdByDataIdAndModelType(record.getId(), 3);
            if (maps != null) {

                List<Object> userLists = Lists.newArrayList();
                Object user_id = maps.get("user_id");
                Object department_id = maps.get("department_id");
                String id = maps.get("id");
                userLists.add(department_id);
                userLists.add(user_id);
                overseasApplyAuditTransferOutListVo.setUserList(userLists);
                overseasApplyAuditTransferOutListVo.setTransferId(id);

            }

            resultList.add(overseasApplyAuditTransferOutListVo);
        }


        IPage<OverseasApplyAuditTransferOutListVo> iPage_1 = new Page<>();
        iPage_1.setRecords(resultList);
        iPage_1.setTotal(iPage.getTotal());
        iPage_1.setPages(iPage.getPages());


        return iPage_1;
    }


    public IPage<OverseasApplyAuditTransferOutListVo> findOverseasApplyAuditTransferInList(OverseasApplyAuditTransferOutListQuery entity) {
        if (entity.getTaskType() == 0) { // 个人任务
            return this.findOverseasApplyPersonalTransferInList(entity);
        }

        IPage<FindRunTaskVo> iPage = getTransferInList(entity);
        if (iPage == null) {
            IPage<OverseasApplyAuditTransferOutListVo> iPage_1 = new Page<>();
            return iPage_1;
        }
        List<OverseasApplyAuditTransferOutListVo> resultList = Lists.newArrayList();
        for (FindRunTaskVo record : iPage.getRecords()) {
            OverseasApplyAuditTransferOutListVo overseasApplyAuditTransferOutListVo = new OverseasApplyAuditTransferOutListVo();
            BeanUtils.copyProperties(record, overseasApplyAuditTransferOutListVo);
            Map<String, String> maps = tbTaskTransferMapper.getUserIdByDataIdAndModelType(record.getProcessTaskId(), 3);
            if (maps != null) {

                List<Object> userLists = Lists.newArrayList();
                Object user_id = maps.get("user_id");
                Object department_id = maps.get("department_id");
                Object receiving_status = maps.get("receiving_status");
                String id = maps.get("id");
                userLists.add(department_id);
                userLists.add(user_id);
                overseasApplyAuditTransferOutListVo.setUserList(userLists);
                overseasApplyAuditTransferOutListVo.setTransferId(id);
                Integer i = StringUtils.toInteger(receiving_status);
                if (i == 0) {
                    resultList.add(overseasApplyAuditTransferOutListVo);
                }

            } else {
                resultList.add(overseasApplyAuditTransferOutListVo);
            }


        }

        IPage<OverseasApplyAuditTransferOutListVo> iPage_1 = new Page<>();
        iPage_1.setRecords(resultList);
        iPage_1.setTotal(iPage.getTotal());
        iPage_1.setPages(iPage.getPages());


        return iPage_1;
    }

    private IPage<OverseasApplyAuditTransferOutListVo> findOverseasApplyPersonalTransferInList(OverseasApplyAuditTransferOutListQuery entity) {

        Page<OverseasApplyAuditTransferOutListVo> page = new Page<>(entity.getPageNum(), entity.getPageSize());
        IPage<OverseasApplyAuditTransferOutListVo> iPage = dao.findOverseasApplyPersonalTransferInList(page, UserUtils.getLoginAppUser().getUserId());
        return iPage;


    }

    private IPage<FindRunTaskVo> getTransferInList(OverseasApplyAuditTransferOutListQuery entity) {
        Page<FindRunTaskVo> page = new Page<>(entity.getPageNum(), entity.getPageSize());

        IPage<GeneralRunTaskVo> iPage = tbPamGeneralProcessTaskMapper.getTransferInData(page, UserUtils.getLoginAppUser().getUserId(), 3);

        List<GeneralRunTaskVo> runTask = iPage.getRecords();

        if (runTask != null && runTask.size() > 0) {
            List<Long> dataIds = runTask.stream().map(generalHiTaskVo -> generalHiTaskVo.getDataId()).collect(Collectors.toList());
            FindRunTaskDto baseParam = new FindRunTaskDto();
            baseParam.setPage(entity.getPageNum());
            baseParam.setSize(entity.getPageSize());


            List<FindRunTaskVo> list = dao.findRunTaskByDataIds(dataIds, baseParam);
            for (FindRunTaskVo findRunTaskVo : list) {
                for (GeneralRunTaskVo generalRunTaskVo : runTask) {
                    if (findRunTaskVo.getDataId().equals(generalRunTaskVo.getDataId())) {
                        // 填充数据
                        findRunTaskVo.setProcessTaskId(generalRunTaskVo.getProcessTaskId());

                        break;
                    }
                }
            }
            IPage<FindRunTaskVo> resultPage = new Page<>();
            resultPage.setRecords(list);
            resultPage.setPages(iPage.getPages());
            resultPage.setTotal(iPage.getTotal());
            return resultPage;
        }
        return null;
    }


    public void deleteDataById(Long id) {
        dao.deleteDataById(id);
    }

    /**
     * @Description: 根据国家名获取数据
     * @Param: PatentListByCountryNameDto
     * @return:
     * @Author: liuqinghua
     * @Date: 2021/6/1
     */
    public IPage<PatentListByCountryNameQuery> getPatentListByCountryName(PatentListByCountryNameDto data) {
        Page<PatentListByCountryNameQuery> page = new Page<>(data.getPage(), data.getSize());
        return dao.getPatentListByCountryName(page, data);
    }

    /**
     * @Description: 国内案件提醒ipr流程专员重新提交
     * @Param: OverseasApplyAuditVo
     * @return:
     * @Author: liuqinghua
     * @Date: 2021/6/18
     */
    public void gmMonitorListReAduit(OverseasApplyAuditVo entity) throws Exception {
        GeneralAuditVo generalAuditVo = this.jointParams(entity);
        if (entity.getStatus() == 0) {
            String ledSeniorProcessEngineer = roleKeyNameProperites.getLedSeniorProcessEngineer();
            Long roleId = userMapper.getRoleIdByRoleKeyName(ledSeniorProcessEngineer);
            if (roleId == null) {
                throw new Exception("LED高级工艺工程师角色不存在,请先完善角色。");
            }
            List<Long> userIdByRoleName = userMapper.getUserIdByRoleName(ledSeniorProcessEngineer);
            if (userIdByRoleName == null || userIdByRoleName.size() == 0)
                throw new Exception("角色-LED高级工艺工程师下无在职用户存在");
            generalAuditVo.setRoleIds(Arrays.asList(roleId));
        }
        TbPamOverseasApply tbPamOverseasApply = new TbPamOverseasApply();
        BeanUtils.copyProperties(entity, tbPamOverseasApply);
        // 处理流程
        tbPamGeneralProcessTaskService.handleProcess(generalAuditVo, generalCallableVo -> {
            tbPamOverseasApply.setNodeId(generalCallableVo.getNodeId());
            tbPamOverseasApply.setNodeName(generalCallableVo.getNodeName());
        });
        this.getDomesticApplyFile(entity.getDisclosureId(), entity.getApplyFileList());
        tbPamOverseasApply.setApplyFileList( entity.getApplyFileList());
        // 保存海外申请数据
        this.saveData(tbPamOverseasApply);
        // 保存专利海外申请国家
        this.saveCountry(entity.getCountryNames(), tbPamOverseasApply.getId());
    }

    /**
     * @Description: 获取审批意见
     * @Param: Long dataId, Long nodeId
     * @return: String
     * @Author: liuqinghua
     * @Date: 2021/6/16
     */
    public List<Map<String, Object>> getOpinionTextByNodeId(Long dataId) {
        GeneralAuditVo generalAuditVo = new GeneralAuditVo();
        generalAuditVo.setDataId(dataId);
        this.fillParams(generalAuditVo);
        return dao.getOpinionTextByNodeId(generalAuditVo);
    }

    /**
     * @Description: 获取节点最新节点
     * @Param: dataId 业务id
     * @return:
     * @Author: liuqinghua
     * @Date: 2021/6/16
     */
    public List<Map<String, Object>> getNewNodeIdByDataId(Long dataId) {
        GeneralAuditVo generalAuditVo = new GeneralAuditVo();
        generalAuditVo.setDataId(dataId);
        this.fillParams(generalAuditVo);
        return dao.getNewNodeIdByDataId(generalAuditVo);
    }

    /**
     * @Description: 保存专利海外申请国家
     * @Param: countryNames-国家列表 dataId-业务id
     * @return:
     * @Author: liuqinghua
     * @Date: 2021/6/18
     */
    public void saveCountry(List<String> countryNames, Long dataId) throws Exception {
        // 删除对应的国家
        tbPamOverseasApplyCountryMapper.deleteByDataId(dataId);
        if (countryNames.size() > 0) {
            String collect = countryNames.stream().collect(Collectors.joining(","));
            TbPamOverseasApplyCountry applyCountry = new TbPamOverseasApplyCountry();
            applyCountry.setDataId(dataId);
            applyCountry.setCountryName(collect);
            applyCountry.setCreateBy(UserUtils.getLoginAppUser().getUserId());
            applyCountry.setCreateDate(new Date());
            int insert = tbPamOverseasApplyCountryMapper.insert(applyCountry);
            if (insert != 1) {
                throw new Exception("保存专利海外申请国家异常");
            }
        }
    }


    /**
     * @Description: 删除我的海外专利
     * @Param: dataId 业务id
     * @return:
     * @Author: liuqinghua
     * @Date: 2021/6/22
     */
    public void deleteMyOverseasApply(Long id) {
        // 删除海外专利申请列表
        dao.deleteDataById(id);
        // 删除正在执行的数据
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("data_id", id);
        tbPamGeneralProcessTaskMapper.deleteByDataId(id);
        // 删除历史表
        tbPamGeneralProcessHiTaskMapper.deleteByDataId(id);

    }


    public void overSeas(String archivesNum,String pArchivesNum,String countryName,int type ) throws Exception {
        List<String> countryNames = Lists.newArrayList(countryName);
        GmMonitorListAduitDto disclosure1 = disclosureMapper.getDisclosureByArchivesNum(pArchivesNum);
        GmMonitorListAduitDto disclosure = disclosureMapper.getDisclosureByArchivesNum(archivesNum);
        String disclosureId = disclosure.getDisclosureId();

        int term = 30;
        Long regionalDetailsId = new Long(2);
        Date priorityDate = null;
        String priorityNum = null;
        MonitorListDto monitorListDto = new MonitorListDto();
        monitorListDto.setArchivesNum(archivesNum);
        monitorListDto.setPageNum(1);
        monitorListDto.setPageSize(10);
        IPage<Map<String, Object>> mapIPage = tbPamOverseasRegionalDetailsService.monitorList(monitorListDto);
        if(mapIPage.getRecords().size()>0) {
            Map<String, Object> records = mapIPage.getRecords().get(0);
              term = Integer.valueOf(String.valueOf(records.get("term"))).intValue();
              regionalDetailsId = new Long(String.valueOf(records.get("regionalDetailsId")));
            priorityDate = (Date) records.get("timeLimitDate");
            priorityNum =  String.valueOf(records.get("applicationNum"));
        }else {
            PatentApplyProject applyProject = patentApplyProjectMapper.getApplyProject(disclosureId);
            if(applyProject != null) {
                priorityNum = applyProject.getApplicationNum();
                priorityDate = applyProject.getApplyDate();
            }
        }
        // 获取对应的交底书ipr
        List<Long> adviceIpr = tbPamInventorProposalIprMapper.getAdviceIpr(disclosureId);
        Long ipr = null;
        if (adviceIpr.size() > 0) {
            ipr = adviceIpr.get(0);
        }else {
            ipr = new Long(290);
//            throw new Exception("ipr不能为空");
        }

        GmMonitorListAduitDto param = new GmMonitorListAduitDto();
        BeanUtils.copyProperties(disclosure,param);
        param.setTerm(term);
        param.setIpr(ipr);
        param.setStatus(0);
        param.setOpinionText("原国内案件转海外");
        param.setRegionalDetailsId(regionalDetailsId);
        param.setArchivesNum(pArchivesNum);
        param.setCountryNames(countryNames);
        param.setPriorityNum(priorityNum);
        param.setPriorityDate(priorityDate);
        param.setDisclosureId(disclosure1.getDisclosureId());
        // 流程1  priorityDate  priorityNum
        TbPamOverseasApply tbPamOverseasApply = this.gmMonitorListAduit(param);

        TimeUnit.SECONDS.sleep(1);
        // 2
        EnterCountryVo enterCountryVo = new EnterCountryVo();
        BeanUtils.copyProperties(tbPamOverseasApply,enterCountryVo);
        enterCountryVo.setStatus(0);
        enterCountryVo.setApplyUserId(new Long(1052));
        enterCountryVo.setCountryNames(countryNames);
        enterCountryVo.setOpinionText("原国内案件转海外");
        TbPamOverseasApply tbPamOverseasApply1 = this.handleProcessNode_10(enterCountryVo);

        TbPamGeneralProcessHiTask hiTask = new TbPamGeneralProcessHiTask();
        List<Long> userIdByRoleName = userMapper.getUserIdByRoleName( roleKeyNameProperites.getLedSeniorProcessEngineer());
        Long aLong = userIdByRoleName.get(0);
        hiTask.setId(tbPamOverseasApply.getProcessTaskId());
        hiTask.setUserId(aLong);

        hiTask.setRoleId(null);
        hiTask.setUpdateBy(aLong);
        hiTask.setUpdateDate(new Date());
        hiTask.setRemarks("原国内案件转海外");
        hiTask.setExamineStatus(1);
        tbPamGeneralProcessHiTaskMapper.updateById(hiTask, "tb_pam_general_process_hi_task");

        TimeUnit.SECONDS.sleep(1);
        // 3
        EnterCountryVo enterCountryVo3 = new EnterCountryVo();
        BeanUtils.copyProperties(tbPamOverseasApply1, enterCountryVo3);
        enterCountryVo3.setStatus(0);
        enterCountryVo3.setOpinionText("原国内案件转海外");
        enterCountryVo3.setCountryNames(countryNames);
        enterCountryVo3.setApplyUserId(new Long(1052));
        TbPamOverseasApply tbPamOverseasApply2 = this.handleProcessNode_11(enterCountryVo3);

        TbPamGeneralProcessHiTask hiTask1 = new TbPamGeneralProcessHiTask();
        String generalManager = roleKeyNameProperites.getGeneralManager();
        List<Long> userIdByRoleName1 = userMapper.getUserIdByRoleName(generalManager);
        Long aLong1 = userIdByRoleName1.get(0);
        hiTask1.setId(tbPamOverseasApply1.getProcessTaskId());
        hiTask1.setUserId(aLong1);
        hiTask1.setRoleId(null);
        hiTask1.setUpdateBy(aLong1);
        hiTask1.setUpdateDate(new Date());
        hiTask1.setRemarks("原国内案件转海外");
        hiTask1.setExamineStatus(1);
        tbPamGeneralProcessHiTaskMapper.updateById(hiTask1, "tb_pam_general_process_hi_task");


        tbPamOverseasApply.setNodeId( tbPamOverseasApply2.getNodeId());
        tbPamOverseasApply.setNodeName( tbPamOverseasApply2.getNodeName());
        tbPamOverseasApply.setProcessTaskId( tbPamOverseasApply2.getProcessTaskId());
        BeanUtils.copyProperties(tbPamOverseasApply, tbPamOverseasApply2);
        tbPamOverseasApply2.setArchivesNum(pArchivesNum);
        TimeUnit.SECONDS.sleep(1);

//        立案
        OverseasApplyAuditVo entity = new OverseasApplyAuditVo();
//        tbPamOverseasApply.setNodeId( tbPamOverseasApply1.getNodeId());
//        tbPamOverseasApply.setNodeName( tbPamOverseasApply1.getNodeName());
//        tbPamOverseasApply.setProcessTaskId( tbPamOverseasApply1.getProcessTaskId());
//        BeanUtils.copyProperties(tbPamOverseasApply1, tbPamOverseasApply);
        BeanUtils.copyProperties(tbPamOverseasApply2, entity);
        entity.setStatus(0);
        entity.setOpinionText("原国内案件转海外");
        entity.setCountryNames(countryNames);
        entity.setIpr(ipr);
        entity.setName(disclosure.getDisclosureName());
        TbPamOverseasApply tbPamOverseasApply3 = handleProcessNode_2(entity);
        tbPamOverseasApply3.setOverseasApplyNum(archivesNum);
        tbPamOverseasApply3.setIpr(ipr);

        String assistantName = roleKeyNameProperites.getAssistantName();
        List<Long> userIdByRoleName3 = userMapper.getUserIdByRoleName(assistantName);
        TbPamGeneralProcessHiTask hiTask3 = new TbPamGeneralProcessHiTask();
        hiTask3.setId(tbPamOverseasApply2.getProcessTaskId());
        hiTask3.setUserId(userIdByRoleName3.get(0));
        hiTask3.setRoleId(null);
        hiTask3.setUpdateBy(userIdByRoleName3.get(0));
        hiTask3.setUpdateDate(new Date());
        hiTask3.setRemarks("原国内案件转海外");
        hiTask3.setExamineStatus(1);
        tbPamGeneralProcessHiTaskMapper.updateById(hiTask3, "tb_pam_general_process_hi_task");

        TimeUnit.SECONDS.sleep(1);


//        IPR撰写申请
        OverseasApplyAuditVo entity3 = new OverseasApplyAuditVo();
        BeanUtils.copyProperties(tbPamOverseasApply3, entity3);
        entity3.setStatus(0);
        entity3.setOpinionText("原国内案件转海外");
        TbPamOverseasApply tbPamOverseasApply4 = handleProcessNode_3(entity3);


        TbPamGeneralProcessHiTask hiTask4 = new TbPamGeneralProcessHiTask();
        hiTask4.setId(tbPamOverseasApply3.getProcessTaskId());
        hiTask4.setUserId(ipr);
        hiTask4.setRoleId(null);
        hiTask4.setUpdateBy(ipr);
        hiTask4.setUpdateDate(new Date());
        hiTask4.setRemarks("原国内案件转海外");
        hiTask4.setExamineStatus(1);
        tbPamGeneralProcessHiTaskMapper.updateById(hiTask4, "tb_pam_general_process_hi_task");

        TimeUnit.SECONDS.sleep(1);
//        主管审核
        OverseasApplyAuditVo entity4 = new OverseasApplyAuditVo();
        BeanUtils.copyProperties(tbPamOverseasApply4, entity4);
        entity4.setStatus(0);
        entity4.setOpinionText("原国内案件转海外");
        TbPamOverseasApply tbPamOverseasApply5 = this.handleProcessNode_4_5(entity4);

        TbPamGeneralProcessHiTask hiTask2 = new TbPamGeneralProcessHiTask();
       String roleName = roleKeyNameProperites.getZszl1();
        List<Long> userIdByRoleName2 = userMapper.getUserIdByRoleName(roleName);
        hiTask2.setId(tbPamOverseasApply4.getProcessTaskId());
        hiTask2.setUserId(userIdByRoleName2.get(0));
        hiTask2.setRoleId(null);
        hiTask2.setUpdateBy(userIdByRoleName2.get(0));
        hiTask2.setUpdateDate(new Date());
        hiTask2.setRemarks("原国内案件转海外");
        hiTask2.setExamineStatus(1);
        tbPamGeneralProcessHiTaskMapper.updateById(hiTask2, "tb_pam_general_process_hi_task");

        TimeUnit.SECONDS.sleep(1);
        if(type == 1) {
            //        总经理审核(提交) CT/CN2020/133331
            OverseasApplyAuditVo entity5 = new OverseasApplyAuditVo();
            BeanUtils.copyProperties(tbPamOverseasApply5, entity5);
            entity5.setOpinionText("原国内案件转海外");
            entity5.setStatus(0);
            TbPamOverseasApply tbPamOverseasApply6 = this.handleProcessNode_4_5(entity5);

            TbPamGeneralProcessHiTask hiTask5 = new TbPamGeneralProcessHiTask();
            String assistantName1 = roleKeyNameProperites.getGeneralManager();
            List<Long> userIdByRoleName5 = userMapper.getUserIdByRoleName(assistantName1);
            hiTask5.setId(tbPamOverseasApply5.getProcessTaskId());
            hiTask5.setUserId(userIdByRoleName5.get(0));
            hiTask5.setRoleId(null);
            hiTask5.setUpdateBy(userIdByRoleName5.get(0));
            hiTask5.setUpdateDate(new Date());
            hiTask5.setRemarks("原国内案件转海外");
            hiTask5.setExamineStatus(1);
            tbPamGeneralProcessHiTaskMapper.updateById(hiTask5, "tb_pam_general_process_hi_task");


//        委托/申请
//            OverseasApplyAuditVo entity6 = new OverseasApplyAuditVo();
//            BeanUtils.copyProperties(tbPamOverseasApply6, entity6);
//            entity6.setStatus(0);
//            entity5.setOpinionText("原国内案件转海外");
//            handleProcessNode_6(entity6);
        }

        // 假删除国内技术
        disclosureMapper.deleteByDisclosureId(disclosureId);
//        审查/反馈

    }

}
